// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_dao

import (
	"encoding/binary"

	"github.com/dgraph-io/badger/v4"
)

const (
	_STATE_NAME_SPACE = "state"
)

type _StateDao struct {
	dbh *badger.DB
}

func (db *_StateDao) Get() (bool, error) {
	txn := db.dbh.NewTransaction(false)
	defer txn.Discard()

	item, err := txn.Get([]byte(_STATE_NAME_SPACE))
	if err != nil {
		if err == badger.ErrKeyNotFound {
			return false, nil
		}
		return false, err
	}
	if item.IsDeletedOrExpired() {
		return false, nil
	}
	value, err := item.ValueCopy(nil)
	if err != nil {
		return false, err
	}

	v := binary.BigEndian.Uint16(value)
	return v != 0, nil
}

func (db *_StateDao) Set(enable bool) error {
	txn := db.dbh.NewTransaction(true)
	defer txn.Discard()

	value := make([]byte, 2, 2)
	if enable {
		binary.BigEndian.PutUint16(value, 1)
	} else {
		binary.BigEndian.PutUint16(value, 0)
	}

	err := txn.Set([]byte(_STATE_NAME_SPACE), value)
	if err != nil {
		return err
	}
	return txn.Commit()
}
